//
//  FindViewController.m
//  Find demo
//
//  Created by 温冬 on 15/6/4.
//  Copyright (c) 2015年 Sound Lab. All rights reserved.
//

#import "FindViewController.h"
#import "Pictures.h"
#import "Find_ContentView.h"
#import "Find_ActivityView.h"
#import "PersonView.h"
#import "Player_ShowModel.h"
#import "search_viewController.h"
//#import "PlayerViewController.h"
#import "playerTableViewController.h"
#import "userInformationViewController.h"
#import "RecordViewController.h"
#import "moreLabxController.h"
#import "popTableviewCell.h"

#import "UIImageView+WebCache.h"
#import "UIViewController+MMDrawerController.h"

#import "AFNetworking.h"
#import "AMPopTip.h"
#import "MobClick.h"
#import "JCAlertView.h"

@interface FindViewController ()<UIScrollViewDelegate, UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    float offset;
    NSString *labXSelectPop;
    NSString *topicSelectPop;
    NSArray *popArray;
}
@property (strong, nonatomic) Find_ActivityView *activityView;
@property (strong, nonatomic) PersonView *personView;
@property (nonatomic, strong) AMPopTip *popTip;
@property (strong, nonatomic) UITableView *popTableview;
@property (strong, nonatomic) UIScrollView *bigScroll;
@property (strong, nonatomic) UIButton *musician;
@property (strong, nonatomic) UIButton *content;
@property (strong, nonatomic) UIButton *leftBtn;
@end

@implementation FindViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToUser:) name:@"findGotoUser" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoPlayer:) name:@"gotoPlayer" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAttentionInfo:) name:@"find_reload" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hidePopTip:) name:@"hidePopview" object:nil];
        popArray = [NSArray arrayWithObjects:@{@"id":@"0",@"name":@"全部"},
                    @{@"id":@"1",@"name":@"音乐"},
                    @{@"id":@"2",@"name":@"生活方式"},
                    @{@"id":@"3",@"name":@"极客"},
                    @{@"id":@"0",@"name":@"其他"}, nil];
        [self requestPopData];
    }
    return self;
}
- (void)requestPopData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *head = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:head forHTTPHeaderField:@"authorization"];
    [manager GET:@"http://123.57.1.143/api/user/type" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray *temp = [NSMutableArray arrayWithArray:(NSArray *)responseObject];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"id",@"全部",@"name", nil];
        //  @{@"id":@"0",@"name":@"全部"};
        [temp insertObject:dic atIndex:0];
        popArray = [NSArray arrayWithArray:temp];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    
    self.leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftBtn.frame = CGRectMake(0, 0, 30, 30);
    [_leftBtn setBackgroundImage:[UIImage imageNamed:@"find_activity_menu"] forState:UIControlStateNormal];
    [_leftBtn addTarget:self action:@selector(popTipShowHide:) forControlEvents:UIControlEventTouchUpInside];
    _leftBtn.tag = 69;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:_leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    _leftBtn.hidden = YES;
    
    self.popTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width *0.28, popArray.count * 44) style:UITableViewStylePlain];
    _popTableview.delegate = self;
    _popTableview.dataSource = self;
    _popTableview.backgroundColor = [UIColor blackColor];
    _popTableview.separatorColor = [UIColor clearColor];
    
    self.popTip = [AMPopTip popTip];
    self.popTip.shouldDismissOnTap = YES;
    self.popTip.edgeMargin = 20;
    self.popTip.offset = 2;
    self.popTip.radius = 0;
    self.popTip.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.popTip.shouldDismissOnTap = YES;
    [self createButton];
    [self createContentActivityView];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [MobClick beginLogPageView:@"发现"];
    [self hidePopTip:nil];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
//    NSString *value = [[NSUserDefaults standardUserDefaults] valueForKey:@"is_find_first"];
//    if (!value) {
//        UIImageView *gird = [[UIImageView alloc] initWithFrame:[AppDelegate shareDelegate].window.bounds];
//        gird.userInteractionEnabled = YES;
//    if ([UIScreen mainScreen].bounds.size.width == 320) {
//        gird.image = [UIImage imageNamed:@"findGird1_5s"];
//    } else if ([UIScreen mainScreen].bounds.size.width == 375) {
//        gird.image = [UIImage imageNamed:@"findGird1_6"];
//    } else {
//        gird.image = [UIImage imageNamed:@"findGird1_6p"];
//    }
//        gird.tag = 1;
//        gird.alpha = 0;
//        [UIView animateWithDuration:1 animations:^{
//            gird.alpha = 1;
//        } completion:^(BOOL finished) {
//            
//        }];
//        [[AppDelegate shareDelegate].window addSubview:gird];
//    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeGird:)];
//        [gird addGestureRecognizer:recognizer];
//    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
//    [self hidePopTip:nil];
    [MobClick endLogPageView:@"发现"];
}
//- (void)changeGird:(UIPanGestureRecognizer *)recognizer
//{
//    UIImageView *image = (UIImageView *)recognizer.view;
//    if (image.tag == 1) {
//        CATransition *transition = [CATransition animation];
//        transition.duration = 0.5f;
//        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
//        transition.delegate = self;
//        transition.type = kCATransitionFade;
//        [image.layer addAnimation:transition forKey:nil];
//        if ([UIScreen mainScreen].bounds.size.width == 320) {
//            image.image = [UIImage imageNamed:@"findGird2_5s"];
//        } else if ([UIScreen mainScreen].bounds.size.width == 375) {
//            image.image = [UIImage imageNamed:@"findGird2_6"];
//        } else {
//            image.image = [UIImage imageNamed:@"findGird2_6p"];
//        }
//        image.tag = 2;
//    } else {
//        [UIView animateWithDuration:0.5 animations:^{
//            image.alpha = 0;
//        } completion:^(BOOL finished) {
//            [image removeGestureRecognizer:recognizer];
//            [image removeFromSuperview];
//        }];
//        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"is_find_first"];
//    }
//}
#pragma mark - 创建导航栏按钮
- (void)createButton
{
    self.content = [UIButton buttonWithType:UIButtonTypeCustom];
    _content.frame = CGRectMake(0, 0, 60, 30);
    [_content  setTitle:@"项目" forState:UIControlStateNormal];
    [_content setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [_content addTarget:self action:@selector(content:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_content];

    self.musician = [UIButton buttonWithType:UIButtonTypeCustom];
    _musician.frame = CGRectMake(60, 0, 60, 30);
    [_musician  setTitle:@"人物" forState:UIControlStateNormal];
    _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [_musician setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
    [_musician addTarget:self action:@selector(musician:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_musician];
    
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    [buttonView addSubview:_content];
    [buttonView addSubview:_musician];
    self.navigationItem.titleView = buttonView;
    
    UIButton *seaechItem = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [seaechItem setImage:[UIImage imageNamed:@"search@3x"] forState:UIControlStateNormal];
    [seaechItem addTarget:self action:@selector(findSeaechClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:seaechItem];
    self.navigationItem.rightBarButtonItem=rightItem;
}
- (void)findSeaechClick
{
    if ([self.popTip isVisible]) {
        [self.popTip hide];
//        return;
    }

    search_viewController *searchVC = [[search_viewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (void)popTipShowHide:(UIButton *)sender
{
    if ([self.popTip isVisible]) {
        [self.popTip hide];
        return;
    }
    if (_bigScroll.contentOffset.x == 0) {
//        _popTableview.frame = CGRectMake(0, 0, self.view.frame.size.width *0.28, popTopicArray.count * 44);
    } else {
        _popTableview.frame = CGRectMake(0, 0, self.view.frame.size.width *0.38, popArray.count * 44);
    }
    [_popTableview reloadData];
    self.popTip.popoverColor = [UIColor blackColor];
    self.popTip.edgeMargin = sender.center.x;
    self.popTip.arrowSize = CGSizeMake(20, 10);
    [self.popTip showCustomView:_popTableview direction:AMPopTipDirectionDown inView:self.view fromFrame:CGRectMake(sender.center.x, 0, 0, 0)];
}
- (void)hidePopTip:(NSNotification *)notification
{
    if ([self.popTip isVisible]) {
        [self.popTip hide];
    }
}
- (void)content:(UIButton *)button
{
//    _leftBtn.hidden = YES;
    if ([self.popTip isVisible]) {
        [self.popTip hide];
    }
    [_bigScroll setContentOffset:CGPointZero animated:YES];
    _leftBtn.hidden = YES;
    [_content setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_musician setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
    _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _bigScroll.scrollsToTop = NO;
//    _contentView.ContentTableView.scrollsToTop = YES;
//    _activityView.ActivityTableView.scrollsToTop = NO;
}
- (void)musician:(UIButton *)button
{
//    _leftBtn.hidden = NO;
    if ([self.popTip isVisible]) {
        [self.popTip hide];
    }
    _leftBtn.hidden = NO;
    [_bigScroll setContentOffset:CGPointMake(self.view.frame.size.width, 0) animated:YES];
    [_musician setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_content setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
    _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _bigScroll.scrollsToTop = NO;
//    _contentView.ContentTableView.scrollsToTop = NO;
//    _activityView.ActivityTableView.scrollsToTop = YES;
}
- (void)createContentActivityView
{
    self.bigScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 48)];

    _bigScroll.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    _bigScroll.delegate = self;
    _bigScroll.scrollEnabled = NO;
    _bigScroll.scrollsToTop = NO;
    _bigScroll.showsHorizontalScrollIndicator = NO;
    _bigScroll.pagingEnabled = YES;
    offset = _bigScroll.contentOffset.x;
    [self.view addSubview:_bigScroll];

    self.activityView = [[Find_ActivityView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 48)popTip:self.popTip];
    _activityView.ActivityTableView.scrollsToTop = NO;
    [_bigScroll addSubview:_activityView];
    __weak FindViewController *selfvc = self;
    _activityView.moreLabxBlock = ^(NSString *type_id){
        moreLabxController *moreLabx = [[moreLabxController alloc] initWithTypeid:type_id];
        [selfvc.navigationController pushViewController:moreLabx animated:YES];
    };
    //内容
    self.personView = [[PersonView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 48)];
    //    _contentView.backgroundColor = [UIColor redColor];
    [_bigScroll addSubview:_personView];
    
//活动
}
- (void)goToUser:(NSNotification *)notification
{
    if ([_popTip isVisible]) {
        [_popTip hide];
        return;
    }
    NSString *userId = notification.object;
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取字典类型NSDictionary类型的数据
    NSString *uid = [userDefaultes stringForKey:@"uid"];
    if (![userId isEqualToString: uid] ) {
        userInformationViewController *otherSelfVC = [[userInformationViewController alloc]initWithSelfUid:userId];
        [self.navigationController pushViewController:otherSelfVC animated:YES];
    }else if([userId isEqualToString: uid]){
        //自动跳到我的
        if (self.tabBarController.selectedIndex == 4) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [self.tabBarController setSelectedIndex:4];
        }
    }
}
- (void)gotoPlayer:(NSNotification *)notification
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isPlay = [userDefaults objectForKey:@"isWiFiPlay"];
    NSString *pppp=[NSString stringWithFormat:@"%u",[self getNetworkTypeFromStatusBar]];
    
    if (([isPlay isEqualToString:@"1"]&&[pppp isEqualToString:@"5"])||[pppp isEqualToString:@"5"]||([isPlay isEqualToString:@"0"]&&![pppp isEqualToString:@"0"])||isPlay==nil) {
    NSString *CinemeID = notification.object;
    Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
    UINavigationController *nv = (UINavigationController *)self.mm_drawerController.rightDrawerViewController;
    playerTableViewController *player = (playerTableViewController *)nv.topViewController;
    NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", CinemeID];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSDictionary *dataDic = [dic valueForKey:@"data"];
            NSDictionary *linksDic = [dic valueForKey:@"links"];
            [playModel setValuesForKeysWithDictionary:dataDic];
            if ([[dic allKeys] containsObject:@"meta"]) {
                NSDictionary *meta = [dic valueForKey:@"meta"];
                NSString *userAvatar = [meta valueForKey:@"userAvatar"];
                player.locUserAvatar = userAvatar;
//                NSArray *array = [meta valueForKey:@"playlist"];
//                player.playList = [NSMutableArray arrayWithArray:array]
                ;
                playModel.comment_count = [meta valueForKey:@"count"];
                ;
            }
            player.waveform = [linksDic valueForKey:@"waveform"];
            player.workID = CinemeID;
            player.isSelf = NO;
            //        if (isCinemeIDPlay == NO) {
            [player reloadViews:playModel];
            //        }
            [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
            }];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    } else {
        [JCAlertView showOneButtonWithTitle:@"你已开启仅Wifi环境播放" Message:@"可以去设置关闭此功能" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];

    }
}
-(NETWORK_state)getNetworkTypeFromStatusBar {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {
            dataNetworkItemView = subview;
            break;
        }
    }
    NETWORK_state nettype = NETWORK_state_NONE;
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    nettype = [num intValue];
    return nettype;
}


#pragma mark -
#pragma mark scroll
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{

//    if ([scrollView.nextResponder isKindOfClass:[UIView class]]) {
//        if (scrollView.contentOffset.x - offset > 0) {
//            [_musician setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [_content setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
//            _content.titleLabel.font = [UIFont boldSystemFontOfSize:16];
//            _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
//        } else {
//            [_content setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [_musician setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
//            _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
//            _musician.titleLabel.font = [UIFont boldSystemFontOfSize:16];
//        }
//    }
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    offset = scrollView.contentOffset.x;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    offset = scrollView.contentOffset.x;
}
#pragma mark -
#pragma mark tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_bigScroll.contentOffset.x == 0) {
        return 0;
    } else {
        return popArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *identifier = @"pop";
    popTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[popTableviewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor blackColor];
    
    cell.content.text = [NSString stringWithFormat:@"%@",[popArray[indexPath.row] valueForKey:@"name"]];
    if ([topicSelectPop isEqualToString:cell.content.text]) {
        cell.selectImage.hidden = NO;
    } else {
        cell.selectImage.hidden = YES;
        if (topicSelectPop == nil && [cell.content.text isEqualToString:@"全部"]) {
            cell.selectImage.hidden = NO;
        }
    }
    cell.content.textColor = [UIColor whiteColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.personView.type = [[popArray[indexPath.row] valueForKey:@"id"] integerValue];
    [_personView.musicianArray removeAllObjects];
    topicSelectPop = [popArray[indexPath.row] valueForKey:@"name"];
    [_personView requestData:1 Refreshing:nil];
    [tableView reloadData];
    if ([self.popTip isVisible]) {
        [self.popTip hide];
    }
}
- (void)changeAttentionInfo:(NSNotification *)notification
{
    PersonTableViewCell *cell = notification.object;
    NSIndexPath *path = [_personView.tableView indexPathForCell:cell];
    Musician *musicianInfo = _personView.musicianArray[path.row];
    musicianInfo.relation = @"1";
    [_personView.musicianArray replaceObjectAtIndex:path.row withObject:musicianInfo];
    [_personView.tableView reloadData];
}
@end
